﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using EmailClient.DTO;
using EmailClient.DAO;
using POP.Pop3;
using POP.Mime;
using DevExpress.XtraBars.Ribbon;
using System.IO;
using System.Diagnostics;
using System.Web.UI;
using POP.Mime.Header;
using EmailClient.FilterSpam;
using System.Net;
using System.Net.Sockets;

namespace EmailClient
{
    public partial class FormMain : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        //declare host of Pop3
        public string pop3_host = "";
        //define port of Pop3
        public int pop3_port = 0;
        //declare host of smtp
        public string smtp_host = "";
        //declare port of smtp
        public int smtp_port = 0;
        //declare name of email
        public string emailName;
        //declare password of email
        public string password;
        //declare total of email in your account
        public int totalEmails;
        //declare current page of list email
        public int page;
        //declare Pop3Client
        public Pop3Client pop3Client;
        public string oldPath;
        //bo loc bayes
        public static NaiveBayes naiveBayes;
        //noi dung email khi lay tu internet ve
        private string bodyEmail;
        public static EmailReader emailReader;
        private string emailAddress = "";
        private bool isSpam = false;
        public ComboBox AccountInbox_FormMain
        {
            get
            {
                return cb_Account_Inbox;
            }
            set
            {
                cb_Account_Inbox = value;
            }
        }
        public ComboBox ListAccount_FormMain
        {
            get
            {
                return comboBox_Account;
            }
            set
            {
                comboBox_Account = value;
            }
        }

        public FormMain()
        {
            InitializeComponent();
        }

        private void AddAccountToAccountInbox(string accountName)
        {
            cb_Account_Inbox.Items.Add(accountName);
        }

        //Create new email
        private void barButtonItem1_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            NewEmail newEmail = new NewEmail();
            newEmail.Show();
        }

        private List<string> ListAccount
        {
            get;
            set;
        }
        private List<string> ListFolder
        {
            get;
            set;
        }
        private List<RfcMailAddress> listCc { get; set; }
        private void FormMain_Load(object sender, EventArgs e)
        {
            //get all paramater
            DataTable dt = ParametersDAO.GetAllParameters();
            if (dt.Rows.Count == 0)
                ParametersDAO.InsertParameters(Application.StartupPath);
            groupBox_AddAccount.Visible = false;
            //load all account into combobox account
            cb_Account_Inbox.DataSource = comboBox_Account.DataSource = AccountDAO.GetAllAccount();
            cb_Account_Inbox.ValueMember = comboBox_Account.ValueMember = "EmailAddress";
            cb_Account_Inbox.DisplayMember = comboBox_Account.DisplayMember = "EmailAddress";
            barButtonItem35.Enabled = false;
            //lấy địa chỉ email hiện tại
            emailAddress = cb_Account_Inbox.GetItemText(cb_Account_Inbox.SelectedItem);
            //init filter spam
            naiveBayes = new NaiveBayes(emailAddress);
            if (naiveBayes.sourceDictionarySpam.Count == 0 || naiveBayes.sourceDictionaryNotSpam.Count == 0)
            {
                MessageBox.Show("Please teach spam filter before load data filter spam");
                TeachFilterSpam teachFilterSpam = new TeachFilterSpam(emailAddress);
                teachFilterSpam.StartPosition = FormStartPosition.CenterScreen;
                
                teachFilterSpam.ShowDialog();
            }
            emailReader = new EmailReader();
            //init compose new email
            NewEmail f = new NewEmail();
            f.Hide();
        }
        private List<Email> Emails
        {
            get;
            set;
        }
        private DataTable CreatTableEmails(DataTable dt_Emails)
        {
            dt_Emails.Columns.Add("IsSelect", typeof(Boolean));
            dt_Emails.Columns.Add("MessageID", typeof(string));
            dt_Emails.Columns.Add("From", typeof(string));
            dt_Emails.Columns.Add("To", typeof(string));
            dt_Emails.Columns.Add("CC", typeof(string));
            dt_Emails.Columns.Add("Bcc", typeof(string));
            dt_Emails.Columns.Add("Subject", typeof(string));
            dt_Emails.Columns.Add("DateSent", typeof(DateTime));
            dt_Emails.Columns.Add("Body", typeof(string));
            return dt_Emails;
        }

        //Insert email to datatable
        private DataTable AddEmailToDataTable(DataTable dt, POP.Mime.Message message)
        {
            DataRow dr = dt.NewRow();
            dr["IsSelect"] = false;
            dr["MessageID"] = message.Headers.MessageId;
            dr["Subject"] = message.Headers.Subject;
            dr["From"] = message.Headers.From;
            List<POP.Mime.Header.RfcMailAddress> listTo = new List<POP.Mime.Header.RfcMailAddress>();
            listTo = message.Headers.To;
            string To_address = null;
            foreach (POP.Mime.Header.RfcMailAddress To in listTo)
                To_address += "," + To.ToString();
            if (To_address != null)
                dr["To"] = To_address.Remove(0, 1);

            List<POP.Mime.Header.RfcMailAddress> listCc = new List<POP.Mime.Header.RfcMailAddress>();
            listCc = message.Headers.Cc;
            string Cc_address = null;
            foreach (POP.Mime.Header.RfcMailAddress Cc in listCc)
                Cc_address += "," + Cc.ToString();
            if (Cc_address != null)
                dr["CC"] = Cc_address.Remove(0, 1);

            dr["DateSent"] = message.Headers.DateSent;
            MessagePart messagePart = message.FindFirstHtmlVersion();
            if (messagePart != null)
            {
                dr["Body"] = messagePart.GetBodyAsText(); 
            }
            else
            {
                messagePart = message.FindFirstPlainTextVersion();
                if (messagePart != null)
                {
                    dr["Body"] = messagePart.GetBodyAsText();
                }
            }
            dt.Rows.Add(dr);
            DataView dv = dt.DefaultView;
            dv.Sort = "DateSent DESC";
            dt = dv.ToTable();
            return dt;
        }

        //Get Pop3Client from email account
        private Pop3Client GetPop3Client(string account, Pop3Client pop3Client)
        {
            DataTable dt = AccountDAO.GetAccountByAccountAddress(account);
            password = dt.Rows[0]["Password"].ToString();
            pop3_host = dt.Rows[0]["Pop3Host"].ToString();
            pop3_port = Int32.Parse(dt.Rows[0]["Pop3Port"].ToString());
            pop3Client.Connect(pop3_host, pop3_port, true);
            pop3Client.Authenticate(account, password);
            return pop3Client;
        }

        //Download Email
        private void barButtonItem34_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            progressBarWait.Visible = true;
            Pop3Client pop3Client = new Pop3Client();
            emailName = cb_Account_Inbox.Text;
            try
            {
                pop3Client = GetPop3Client(emailName, pop3Client);
            }
            catch
            {
                MessageBox.Show("Server not found!");
            }
            totalEmails = pop3Client.GetMessageCount();
            DataTable dt_Emails = new DataTable("Emails");
            dt_Emails = CreatTableEmails(dt_Emails);
            dt_Emails = (DataTable)dgv_Inbox.DataSource;
            string pathToFolderSpam = @"EmailDB\" + cb_Account_Inbox.Text + @"\Spam";
            string path = @"EmailDB\" + cb_Account_Inbox.Text + @"\Inbox";
            if (!Directory.Exists(path))
                Directory.CreateDirectory(path);
            progressBarWait.Maximum = totalEmails;
            progressBarWait.Value++;
            int messageNumber = totalEmails;

            while (!File.Exists(path + @"\" + pop3Client.GetMessage(messageNumber).Headers.MessageId + @".eml"))
            {

                POP.Mime.Message message = pop3Client.GetMessage(messageNumber);
                /*lấy nội dung email về
                 */
                MessagePart messagePart = message.FindFirstHtmlVersion();
                if (messagePart != null)
                {
                    bodyEmail = messagePart.GetBodyAsText();
                }
                else
                {
                    messagePart = message.FindFirstPlainTextVersion();
                    if (messagePart != null)
                    {
                        bodyEmail = messagePart.GetBodyAsText();
                    }
                    else
                    {
                        bodyEmail = null;
                    }
                }
                MessageBox.Show(emailReader.StripTagsRegexCompiled(bodyEmail), cb_Account_Inbox.Items[0].ToString());
                //isSpam = naiveBayes.CheckEmail(emailReader.StripTagsRegexCompiled(bodyEmail), cb_Account_Inbox.Items[0].ToString());
                /*download email về máy tính
                 */
                MessageBox.Show(isSpam.ToString());
                FileStream file = new FileStream(@"EmailDB\NotSpam" + @"\" + pop3Client.GetMessage(messageNumber).Headers.MessageId + @".eml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                message.Save(file);
                file.Close();

                /*
                if (!isSpam)
                {
                    FileStream file = new FileStream(path + @"\" + pop3Client.GetMessage(messageNumber).Headers.MessageId + @".eml", FileMode.OpenOrCreate, FileAccess.ReadWrite);
                    message.Save(file);
                    file.Close();
                }*/
                dt_Emails = AddEmailToDataTable(dt_Emails, message);
                /*down attachment
                 */
                List<MessagePart> attachments = message.FindAllAttachments();
                if (attachments != null)
                    foreach (MessagePart attachment in attachments)
                    {
                        string filePath_attachment = @"EmailDB\" + cb_Account_Inbox.Text + @"\Attachments\" + attachment.FileName;
                        if (!File.Exists(filePath_attachment))
                        {
                            FileInfo fileInf = new FileInfo(filePath_attachment);
                            attachment.Save(fileInf);
                        }
                    }
                messageNumber--;
                if (messageNumber < 1)
                    break;
            }
            /*
             * hiển thị thông tin lên màn hình
             */
            dgv_Inbox.DataSource = dt_Emails;
            cb_Account_Inbox.Text = emailName;
            progressBarWait.Visible = false;
        }

        private void backstageViewButtonItemExit_ItemClick_Exit(object sender, BackstageViewItemEventArgs e)
        {
            Application.Exit();
        }

        private void btn_AddAccount_Click(object sender, EventArgs e)
        {
            groupBox_AddAccount.Visible = true;
            label_checkPassword.Visible = false;
            label_checkEmail.Visible = false;
        }

        //Bookmark Non-Spam
        private void barButtonItem35_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            for (int i = dgv_Inbox.Rows.Count - 1; i >= 0; i--)
            {
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected ||
                    Convert.ToBoolean(dgv_Inbox.Rows[i].Cells["Selected"].Value) == true)
                {
                    string messageID = dgv_Inbox.Rows[i].Cells["MessageID"].Value.ToString();
                    if (messageID != "")
                    {
                        string filePath = @"EmailDB\" + cb_Account_Inbox.Text + @"\Spam\" + messageID + @".eml";
                        File.Move(filePath, @"EmailDB\" + cb_Account_Inbox.Text + @"\Inbox\" + messageID + @".eml");
                        dgv_Inbox.Rows.RemoveAt(i);
                    }
                }
            }
        }

        //Bookmark spam
        private void barButtonItem36_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!Directory.Exists(@"EmailDB\" + cb_Account_Inbox.Text + @"\Spam"))
                Directory.CreateDirectory(@"EmailDB\" + cb_Account_Inbox.Text + @"\Spam");
            for (int i = dgv_Inbox.Rows.Count - 1; i >= 0; i--)
            {
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected ||
                    Convert.ToBoolean(dgv_Inbox.Rows[i].Cells["Selected"].Value) == true)
                {
                    string messageID = dgv_Inbox.Rows[i].Cells["MessageID"].Value.ToString();
                    if (messageID != "")
                    {
                        string filePath = @"EmailDB\" + cb_Account_Inbox.Text + @"\Inbox\" + messageID + @".eml";
                        File.Move(filePath, @"EmailDB\" + cb_Account_Inbox.Text + @"\Spam\" + messageID + @".eml");
                        dgv_Inbox.Rows.RemoveAt(i);
                    }
                }
            }
        }

        //Reply Email
        private void barButtonItem5_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            for (int i = 0; i < dgv_Inbox.Rows.Count; i++)
            {
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected)
                {
                    NewEmail newEmail = new NewEmail();
                    string from = dgv_Inbox.Rows[i].Cells["From"].Value.ToString();
                    if (from.Contains("<") && from.Contains(">"))
                    {
                        string fromAddress = from.Substring(from.LastIndexOf("<") + 1);
                        newEmail.txt_To.Text = fromAddress.Remove(fromAddress.Length - 1);
                    }
                    else
                        newEmail.txt_To.Text = from;
                    newEmail.cb_From.Text = emailName;
                    newEmail.txt_Subject.Text = dgv_Inbox.Rows[i].Cells["Subject"].Value.ToString();
                    newEmail.ShowDialog();
                }
            }
        }

        //Click Choose Account
        private void cb_Account_Inbox_SelectedIndexChanged(object sender, EventArgs e)
        {
            ToolStripMenuItem_Inbox.Visible = false;
            if (cb_Account_Inbox.Text != "System.Data.DataRowView")
            {
                treeViewFolder.Nodes.Clear();
                DataTable dt_Emails = new DataTable("dt_Emails");
                dt_Emails = CreatTableEmails(dt_Emails);
                string account = cb_Account_Inbox.Text;
                string path = @"EmailDB\" + account + @"\Inbox";
                dgv_Inbox.DataSource = ListEmailFromFile(dt_Emails, path);
                dt_Emails = ListEmailFromFile(dt_Emails, path);

                ListFolder = new List<string>();
                List<string> directories = Directory.GetDirectories(@"EmailDB\" + account).ToList();
                foreach (string directory in directories)
                {
                    string[] folders = directory.Split(@"\".ToCharArray());
                    string folder = folders[folders.Length - 1];
                    if (folder != "Attachments")
                    {
                        TreeNode node = new TreeNode(folder);
                        treeViewFolder.Nodes.Add(node);
                    }
                }
            }
        }

        //Add email from file
        private DataTable ListEmailFromFile(DataTable dt, string path)
        {
            {
                string[] filePaths = Directory.GetFiles(path);
                if (filePaths != null)
                {
                    foreach (string filePath in filePaths)
                    {
                        FileStream file = new FileStream(filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite);
                        POP.Mime.Message message = POP.Mime.Message.Load(file);
                        dt = AddEmailToDataTable(dt, message);
                        file.Close();
                    }
                    DataView dv = dt.DefaultView;
                    dv.Sort = "DateSent DESC";
                    dt = dv.ToTable();
                    return dt;
                }
                else return null;
            }
        }

        //Delete account
        private void btn_DeleteAccount_Click(object sender, EventArgs e)
        {
            if (MessageBox.Show("Do you want to delete this account?", "Confirm", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes)
                try
                {
                    AccountDAO.DeleteAccount(comboBox_Account.Text);
                    cb_Account_Inbox.DataSource = comboBox_Account.DataSource = AccountDAO.GetAllAccount();
                    cb_Account_Inbox.ValueMember = comboBox_Account.ValueMember = "EmailAddress";
                    cb_Account_Inbox.DisplayMember = comboBox_Account.DisplayMember = "EmailAddress";
                    MessageBox.Show("Delete account successfully!");
                }
                catch
                {
                    MessageBox.Show("Delete account failed");
                }
        }

        //Delete Email
        private void barButtonItem3_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (!Directory.Exists(@"EmailDB\" + cb_Account_Inbox.Text + @"\Deleted Items"))
                Directory.CreateDirectory(@"EmailDB\" + cb_Account_Inbox.Text + @"\Deleted Items");
            for (int i = dgv_Inbox.Rows.Count - 1; i >= 0; i--)
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected ||
                    Convert.ToBoolean(dgv_Inbox.Rows[i].Cells["Selected"].Value) == true)
                {
                    try
                    {
                        string messageID = dgv_Inbox.Rows[i].Cells["MessageID"].Value.ToString();
                        string filePath = @"EmailDB\" + cb_Account_Inbox.Text + @"\Inbox\" + messageID + @".eml";
                        if (File.Exists(filePath))
                            File.Move(filePath, @"EmailDB\" + cb_Account_Inbox.Text + @"\Deleted Items\" + messageID + @".eml");
                        else
                        {
                            filePath = @"EmailDB\" + cb_Account_Inbox.Text + @"\Spam\" + messageID + @".eml";
                            File.Move(filePath, @"EmailDB\" + cb_Account_Inbox.Text + @"\Deleted Items\" + messageID + @".eml");
                        }
                        dgv_Inbox.Rows.RemoveAt(i);
                    }
                    catch
                    {
                        MessageBox.Show("Can't delete email!");
                    }
                }
        }

        //Open attachments
        private void toolStripMenuItemOpen_Click(object sender, EventArgs e)
        {
            foreach (ListViewItem item in List_Attachments.Items)
                if (item.Selected)
                    foreach (string filePath in Directory.GetFiles(@"EmailDB\" + cb_Account_Inbox.Text + @"\Attachments"))
                    {
                        FileInfo fileInf = new FileInfo(filePath);
                        if (item.Tag.ToString().Contains(fileInf.Name))
                            Process.Start(fileInf.FullName);
                    }
        }

        private void List_Attachments_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
                foreach (ListViewItem item in List_Attachments.Items)
                    if (item.Bounds.Contains(e.X, e.Y))
                        popup_AttachFile.Show(Cursor.Position);
        }

        //Open attachments
        private void List_Attachments_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            foreach (ListViewItem item in List_Attachments.Items)
                if (item.Selected)
                    foreach (string filePath in Directory.GetFiles(@"EmailDB\" + cb_Account_Inbox.Text + @"\Attachments"))
                    {
                        FileInfo fileInf = new FileInfo(filePath);
                        if (item.Tag.ToString().Contains(fileInf.Name))
                            Process.Start(fileInf.FullName);
                    }
        }

        //Select all email
        private void barCheckItem1_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            if (barCheckItem1.Checked)
                for (int i = 0; i < dgv_Inbox.Rows.Count - 1; i++)
                    dgv_Inbox.Rows[i].Cells["Selected"].Value = true;
            else
                for (int j = 0; j < dgv_Inbox.Rows.Count - 1; j++)
                    dgv_Inbox.Rows[j].Cells["Selected"].Value = false;
        }
        public bool DeleteMessageByMessageId(Pop3Client client, string messageId)
        {
            int messageCount = client.GetMessageCount();
            for (int messageNumber = messageCount; messageNumber > 0; messageNumber--)
            {
                if (client.GetMessageHeaders(messageNumber).MessageId == messageId)
                {
                    client.DeleteMessage(messageNumber);
                    client.Disconnect();
                    client.Dispose();
                    return true;
                }
            }
            return false;
        }

        private string StripHTML(string source)
        {
            try
            {
                string result;

                // Remove HTML Development formatting
                // Replace line breaks with space
                // because browsers inserts space
                result = source.Replace("\r", " ");
                // Replace line breaks with space
                // because browsers inserts space
                result = result.Replace("\n", " ");
                // Remove step-formatting
                result = result.Replace("\t", string.Empty);
                // Remove repeating spaces because browsers ignore them
                result = System.Text.RegularExpressions.Regex.Replace(result,
                                                                      @"( )+", " ");

                // Remove the header (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*head([^>])*>", "<head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*head( )*>)", "</head>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<head>).*(</head>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // remove all scripts (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*script([^>])*>", "<script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*script( )*>)", "</script>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                //result = System.Text.RegularExpressions.Regex.Replace(result,
                //         @"(<script>)([^(<script>\.</script>)])*(</script>)",
                //         string.Empty,
                //         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<script>).*(</script>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // remove all styles (prepare first by clearing attributes)
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*style([^>])*>", "<style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"(<( )*(/)( )*style( )*>)", "</style>",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(<style>).*(</style>)", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert tabs in spaces of <td> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*td([^>])*>", "\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line breaks in places of <BR> and <LI> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*br( )*>", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*li( )*>", "\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // insert line paragraphs (double line breaks) in place
                // if <P>, <DIV> and <TR> tags
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*div([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*tr([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<( )*p([^>])*>", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // Remove remaining tags like <a>, links, images,
                // comments etc - anything that's enclosed inside < >
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"<[^>]*>", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // replace special characters:
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @" ", " ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&bull;", " * ",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&lsaquo;", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&rsaquo;", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&trade;", "(tm)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&frasl;", "/",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&lt;", "<",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&gt;", ">",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&copy;", "(c)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&reg;", "(r)",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove all others. More can be added, see
                // http://hotwired.lycos.com/webmonkey/reference/special_characters/
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         @"&(.{2,6});", string.Empty,
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // for testing
                //System.Text.RegularExpressions.Regex.Replace(result,
                //       this.txtRegex.Text,string.Empty,
                //       System.Text.RegularExpressions.RegexOptions.IgnoreCase);

                // make line breaking consistent
                result = result.Replace("\n", "\r");

                // Remove extra line breaks and tabs:
                // replace over 2 breaks with 2 and over 4 tabs with 4.
                // Prepare first to remove any whitespaces in between
                // the escaped characters and remove redundant tabs in between line breaks
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\t)", "\t\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\t)( )+(\r)", "\t\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)( )+(\t)", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove redundant tabs
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+(\r)", "\r\r",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Remove multiple tabs following a line break with just one tab
                result = System.Text.RegularExpressions.Regex.Replace(result,
                         "(\r)(\t)+", "\r\t",
                         System.Text.RegularExpressions.RegexOptions.IgnoreCase);
                // Initial replacement target string for line breaks
                string breaks = "\r\r\r";
                // Initial replacement target string for tabs
                string tabs = "\t\t\t\t\t";
                for (int index = 0; index < result.Length; index++)
                {
                    result = result.Replace(breaks, "\r\r");
                    result = result.Replace(tabs, "\t\t\t\t");
                    breaks = breaks + "\r";
                    tabs = tabs + "\t";
                }

                // That's it.
                return result;
            }
            catch
            {
                MessageBox.Show("Error");
                return source;
            }
        }
        //View detail email
        private void dgv_Inbox_CellEnter(object sender, DataGridViewCellEventArgs e)
        {
            List_Attachments.Items.Clear();
            if (dgv_Inbox.DataSource != null)
            {
                webBrowser_MailBody.DocumentText = Convert.ToString(dgv_Inbox.Rows[dgv_Inbox.CurrentRow.Index].Cells["Body"].Value);

                string htmlBody = Convert.ToString(dgv_Inbox.Rows[dgv_Inbox.CurrentRow.Index].Cells["Body"].Value);
                string plainTextBody = StripHTML(htmlBody);

                string dateSent = Convert.ToString(dgv_Inbox.Rows[dgv_Inbox.CurrentRow.Index].Cells["DateSent"].Value);
                string from = Convert.ToString(dgv_Inbox.Rows[dgv_Inbox.CurrentRow.Index].Cells["From"].Value);
                string subject = Convert.ToString(dgv_Inbox.Rows[dgv_Inbox.CurrentRow.Index].Cells["Subject"].Value);
                string to = Convert.ToString(dgv_Inbox.Rows[dgv_Inbox.CurrentRow.Index].Cells["To"].Value);
                string cc = Convert.ToString(dgv_Inbox.Rows[dgv_Inbox.CurrentRow.Index].Cells["CC"].Value);
                txt_EmailInfo.Text = "DateSent: " + dateSent + Environment.NewLine + "From: " + from + Environment.NewLine
                    + "Subject: " + subject + Environment.NewLine + "To: " + to;
                if (cc != "")
                    txt_EmailInfo.Text += Environment.NewLine + "Cc: " + cc;
                string messageId = dgv_Inbox.Rows[dgv_Inbox.CurrentRow.Index].Cells["MessageID"].Value.ToString();
                if (messageId != "")
                {
                    string[] paths = Directory.GetDirectories(@"EmailDB\" + cb_Account_Inbox.Text);
                    foreach (string path in paths)
                    {
                        string[] filePaths = Directory.GetFiles(path);
                        foreach (string filePath in filePaths)
                        {
                            FileStream file = new FileStream(filePath, FileMode.Open, FileAccess.Read);
                            if (file.Name.Contains(messageId))
                            {
                                POP.Mime.Message message = POP.Mime.Message.Load(file);
                                List<MessagePart> attachments = message.FindAllAttachments();
                                //initialize list attachment of email from current message
                                foreach (MessagePart attachment in attachments)
                                {
                                    ListViewItem item = new ListViewItem(attachment.FileName);
                                    item.ImageIndex = 0;
                                    item.Tag = attachment.FileName;
                                    List_Attachments.Items.Add(item);
                                }
                            }
                            file.Close();
                        }
                    }
                }
            }
        }

        private void btn_Cancel_Click(object sender, EventArgs e)
        {
            txt_Email.Text = txt_Password.Text = txt_RePassword.Text = txt_SmtpHost.Text = txt_SmtpPort.Text = txt_Pop3Host.Text = txt_Pop3Port.Text = "";
            groupBox_AddAccount.Visible = false;
        }

        public bool TestSmtp(string host, int port)
        {
           try
           {
              TcpClient tcp = new TcpClient();
              tcp.Connect(host, port);
              return true;
           }
           catch (Exception myException)
           {
              return false;
           }
        }
        //Add new account
        private void btn_Ok_Click(object sender, EventArgs e)
        {
            if (!NewEmail.CheckEmail(txt_Email.Text.Trim()) || txt_Email.Text.Trim() == "")
                label_checkEmail.Visible = true;
            if (txt_Password.Text != txt_RePassword.Text || txt_Password.Text.Trim() == "")
                label_checkPassword.Visible = true;
            else
                if (NewEmail.CheckEmail(txt_Email.Text.Trim()) && txt_SmtpHost.Text != ""
                    && txt_SmtpPort.Text != "" && txt_Pop3Host.Text != "" && txt_Pop3Port.Text != "")
                {
                    {
                        smtp_host = txt_SmtpHost.Text;
                        smtp_port = Int32.Parse(txt_SmtpPort.Text);
                        pop3_host = txt_Pop3Host.Text;
                        pop3_port = Int32.Parse(txt_Pop3Port.Text);
                        if (ConnectServer(pop3_host, pop3_port, txt_Email.Text.Trim(), txt_Password.Text.Trim())
                            && TestSmtp(smtp_host, smtp_port))
                        {
                            try
                            {
                                searchSMTP(txt_Email.Text.Trim());
                                searchPOP3(txt_Email.Text.Trim());
                                string accAddress = txt_Email.Text.Trim();
                                Account acc = new Account();
                                acc.AccountAddress = txt_Email.Text.Trim();
                                acc.Password = txt_Password.Text.Trim();
                                acc.SmtpHost = smtp_host;
                                acc.SmtpPort = smtp_port;
                                acc.Pop3Host = pop3_host;
                                acc.Pop3Port = pop3_port;
                                AccountDAO.AddAccount(acc);

                                string path_Inbox = @"EmailDB\" + accAddress + @"\Inbox";
                                if (!Directory.Exists(path_Inbox))
                                    Directory.CreateDirectory(path_Inbox);
                                string path_Spam = @"EmailDB\" + accAddress + @"\Spam";
                                if (!Directory.Exists(path_Spam))
                                    Directory.CreateDirectory(path_Spam);
                                string path_DeteledItems = @"EmailDB\" + accAddress + @"\Deleted Items";
                                if (!Directory.Exists(path_DeteledItems))
                                    Directory.CreateDirectory(path_DeteledItems);
                                string path_SentItems = @"EmailDB\" + accAddress + @"\Sent Items";
                                if (!Directory.Exists(path_SentItems))
                                    Directory.CreateDirectory(path_SentItems);
                                string path_Attachments = @"EmailDB\" + accAddress + @"\Attachments";
                                if (!Directory.Exists(path_Attachments))
                                    Directory.CreateDirectory(path_Attachments);

                                cb_Account_Inbox.DataSource = comboBox_Account.DataSource = AccountDAO.GetAllAccount();
                                groupBox_AddAccount.Visible = false;
                                txt_Email.Text = txt_Password.Text = txt_RePassword.Text = txt_SmtpHost.Text
                                    = txt_SmtpPort.Text = txt_Pop3Host.Text = txt_Pop3Port.Text = "";
                                MessageBox.Show("Add account successfully!");
                            }
                            catch
                            {
                                MessageBox.Show("This account has been existed or isn't invalid!");
                            }
                        }
                        else
                            MessageBox.Show("Can't connect to server!");
                    }
                }
                else
                {
                    MessageBox.Show("Can't connect to server!");
                }
        }

        public void searchPOP3(string emailAddress)
        {
            pop3_host = null;
            pop3_port = 0;
            if (emailAddress.Contains("@gmail.com"))
            {
                pop3_host = "pop.gmail.com";
                pop3_port = 995;
            }
            if (emailAddress.Contains("@outlook.com") || emailAddress.Contains("@hotmail.com"))
            {
                pop3_host = "pop3.live.com";
                pop3_port = 995;
            }
            if (emailAddress.Contains("@yahoo.com"))
            {
                pop3_host = "pop.mail.yahoo.com";
                pop3_port = 995;
            }
        }
        public void searchSMTP(string emailAddress)
        {
            smtp_host = null;
            smtp_port = 0;
            if (emailAddress.Contains("@gmail.com"))
            {
                smtp_host = "smtp.gmail.com";
                smtp_port = 587;
            }
            if (emailAddress.Contains("@outlook.com") || emailAddress.Contains("@hotmail.com"))
            {
                smtp_host = "smtp.live.com";
                smtp_port = 587;
            }
            if (emailAddress.Contains("@yahoo.com"))
            {
                smtp_host = "smtp.mail.yahoo.com";
                smtp_port = 587;
            }
        }
        public bool ConnectServer(string pop3_host, int po3_port, string emailAddress, string password)
        {
            try
            {
                Pop3Client pop3 = new Pop3Client();
                pop3.Connect(pop3_host, po3_port, true);
                pop3.Authenticate(emailAddress, password);
                return true;
            }
            catch
            {
                return false;
            }
        }

        private void txt_Password_TextChanged(object sender, EventArgs e)
        {
            label_checkPassword.Visible = false;
        }

        private void txt_RePassword_TextChanged(object sender, EventArgs e)
        {
            label_checkPassword.Visible = false;
        }

        private void txt_Email_TextChanged(object sender, EventArgs e)
        {
            label_checkEmail.Visible = false;
            searchPOP3(txt_Email.Text.Trim());
            searchSMTP(txt_Email.Text.Trim());
            if (smtp_port != 0 && pop3_port != 0)
            {
                txt_SmtpHost.Text = smtp_host;
                txt_SmtpPort.Text = smtp_port.ToString();
                txt_Pop3Host.Text = pop3_host;
                txt_Pop3Port.Text = pop3_port.ToString();
            }
            else
            {
                txt_SmtpHost.Text = null;
                txt_SmtpPort.Text = null;
                txt_Pop3Host.Text = null;
                txt_Pop3Port.Text = null;
            }
        }

        private void btn_TeachSpamFilter_Click(object sender, EventArgs e)
        {
            naiveBayes.TeachFilterSpam(@"EmailDB\Spam\", @"EmailDB\NotSpam\", emailReader);
            naiveBayes.SaveFilterSpam(naiveBayes.desDictionarySpam, true);
            naiveBayes.SaveFilterSpam(naiveBayes.desDictionaryNotSpam, false);
        }

        private void btn_AccountSetting_Click(object sender, EventArgs e)
        {
            Setting f = new Setting();
            f.ShowDialog();
        }

        //Click folder in Account
        private void treeViewFolder_AfterSelect(object sender, TreeViewEventArgs e)
        {
            if (treeViewFolder.SelectedNode.Text == "Deleted Items" || treeViewFolder.SelectedNode.Text == "Spam")
                ToolStripMenuItem_Inbox.Visible = true;
            else
                ToolStripMenuItem_Inbox.Visible = false;

            if (!Directory.Exists(@"EmailDB\" + cb_Account_Inbox.Text + @"\" + treeViewFolder.SelectedNode.Text))
                Directory.CreateDirectory(@"EmailDB\" + cb_Account_Inbox.Text + @"\" + treeViewFolder.SelectedNode.Text);

            if (cb_Account_Inbox.Text != "System.Data.DataRowView")
            {
                DataTable dt_Emails = new DataTable("Emails");
                dt_Emails = CreatTableEmails(dt_Emails);
                string folder = e.Node.Text;
                string path = @"EmailDB\" + cb_Account_Inbox.Text + @"\" + folder;
                dgv_Inbox.DataSource = ListEmailFromFile(dt_Emails, path);
                if (folder == "Spam")
                {
                    barButtonItem35.Enabled = true;
                    barButtonItem36.Enabled = false;
                }
                else
                {
                    barButtonItem35.Enabled = false;
                    barButtonItem36.Enabled = true;
                }
            }

            if (treeViewFolder.SelectedNode.Text == "Inbox" || treeViewFolder.SelectedNode.Text == "Spam" || treeViewFolder.SelectedNode.Text
                == "Sent Items" || treeViewFolder.SelectedNode.Text == "Attachments" || treeViewFolder.SelectedNode.Text == "Deleted Items")
            {
                toolStripMenuItem_DeleteFolder.Visible = false;
                toolStripMenuItem_CopyFolder.Visible = false;
                toolStripMenuItem_MoveFolder.Visible = false;
                toolStripMenuItem_RenameFolder.Visible = false;
            }
            else
            {
                toolStripMenuItem_DeleteFolder.Visible = true;
                toolStripMenuItem_CopyFolder.Visible = true;
                toolStripMenuItem_MoveFolder.Visible = true;
                toolStripMenuItem_RenameFolder.Visible = true;
            }
            if (treeViewFolder.SelectedNode.Text == "Deleted Items")
            {
                toolStripMenuItem_Reply.Visible = false;
                toolStripMenuItem_ReplyAll.Visible = false;
                toolStripMenuItem_Forward.Visible = false;
            }
            else
            {
                toolStripMenuItem_Reply.Visible = true;
                toolStripMenuItem_ReplyAll.Visible = true;
                toolStripMenuItem_Forward.Visible = true;
            }
        }

        //Press menu Add new folder
        private void toolStripMenuItem_New_Click(object sender, EventArgs e)
        {
            NewFolder newFolder = new NewFolder();
            newFolder.ShowDialog();
            TreeNode treeNode = new TreeNode();
            treeNode.Text = newFolder.txt_FolderName.Text;
            newFolder.Close();
            if (newFolder.txt_FolderName.Text != "")
            {
                Directory.CreateDirectory(@"EmailDB\" + cb_Account_Inbox.Text + @"\" + treeNode.Text);
                treeViewFolder.Nodes.Add(treeNode);
            }
        }

        //Press menu Rename folder
        private void toolStripMenuItem_Rename_Click(object sender, EventArgs e)
        {
            Directory.Delete(@"EmailDB\" + cb_Account_Inbox.Text + @"\" + treeViewFolder.SelectedNode.Text);
            treeViewFolder.LabelEdit = true;
            treeViewFolder.SelectedNode.BeginEdit();
        }

        //Press menu Delete folder
        private void toolStripMenuItem_Delete_Click(object sender, EventArgs e)
        {
            Directory.Delete(@"EmailDB\" + cb_Account_Inbox.Text + @"\" + treeViewFolder.SelectedNode.Text);
            treeViewFolder.Nodes.Remove(treeViewFolder.SelectedNode);
        }

        //Press button Add new folder
        private void barButtonItem23_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            NewFolder newFolder = new NewFolder();
            newFolder.ShowDialog();
            TreeNode treeNode = new TreeNode();
            treeNode.Text = newFolder.txt_FolderName.Text;
            newFolder.Close();
            if (newFolder.txt_FolderName.Text != "")
            {
                Directory.CreateDirectory(@"EmailDB\" + cb_Account_Inbox.Text + @"\" + treeNode.Text);
                treeViewFolder.Nodes.Add(treeNode);
            }
        }

        //Press button Rename folder
        private void barButtonItem25_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Directory.Delete(@"EmailDB\" + cb_Account_Inbox.Text + @"\" + treeViewFolder.SelectedNode.Text);
            treeViewFolder.LabelEdit = true;
            treeViewFolder.SelectedNode.BeginEdit();
        }

        //Press button Delete folder
        private void barButtonItem28_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            Directory.Delete(@"EmailDB\" + cb_Account_Inbox.Text + @"\" + treeViewFolder.SelectedNode.Text);
            treeViewFolder.Nodes.Remove(treeViewFolder.SelectedNode);
        }

        private void dgv_Inbox_MouseDown(object sender, MouseEventArgs e)
        {
            if (e.Button == MouseButtons.Right)
                contextMenuStrip_Message.Show(Cursor.Position);
        }

        //Press menu Delete email
        private void toolStripMenuItem5_Click(object sender, EventArgs e)
        {
            if (!Directory.Exists(@"EmailDB\" + cb_Account_Inbox.Text + @"\Deleted Items"))
                Directory.CreateDirectory(@"EmailDB\" + cb_Account_Inbox.Text + @"\Deleted Items");
            for (int i = dgv_Inbox.Rows.Count - 1; i >= 0; i--)
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected ||
                    Convert.ToBoolean(dgv_Inbox.Rows[i].Cells["Selected"].Value) == true)
                {
                    try
                    {
                        string messageID = dgv_Inbox.Rows[i].Cells["MessageID"].Value.ToString();
                        string filePath = @"EmailDB\" + cb_Account_Inbox.Text + @"\Inbox\" + messageID + @".eml";
                        if (File.Exists(filePath))
                            File.Move(filePath, @"EmailDB\" + cb_Account_Inbox.Text + @"\Deleted Items\" + messageID + @".eml");
                        else
                        {
                            filePath = @"EmailDB\" + cb_Account_Inbox.Text + @"\Spam\" + messageID + @".eml";
                            File.Move(filePath, @"EmailDB\" + cb_Account_Inbox.Text + @"\Deleted Items\" + messageID + @".eml");
                        }
                        dgv_Inbox.Rows.RemoveAt(i);
                    }
                    catch
                    {
                        MessageBox.Show("Can't delete email!");
                    }
                }
        }

        private void barButtonItem39_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            /*
             * Teach spam filter and save into database
             */
            naiveBayes.TeachFilterSpam(@"EmailDB\Spam", @"EmailDB\NotSpam", emailReader);
        }

        private void barCheckItem2_CheckedChanged(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            /*
             * Active filter spam
             * Load filter spam in here
             */

        }

        private void ToolStripMenuItem_Inbox_Click(object sender, EventArgs e)
        {
            for (int i = dgv_Inbox.Rows.Count - 1; i >= 0; i--)
            {
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected ||
                    Convert.ToBoolean(dgv_Inbox.Rows[i].Cells["Selected"].Value) == true)
                {
                    string messageID = dgv_Inbox.Rows[i].Cells["MessageID"].Value.ToString();
                    if (messageID != "")
                    {
                        string folder = treeViewFolder.SelectedNode.Text;
                        string oldPath = @"EmailDB\" + cb_Account_Inbox.Text + @"\" + folder + @"\" + messageID + @".eml";
                        File.Move(oldPath, @"EmailDB\" + cb_Account_Inbox.Text + @"\Inbox\" + messageID + @".eml");
                        dgv_Inbox.Rows.RemoveAt(i);
                    }
                }
            }
        }

        //Reply all
        private void barButtonItem6_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            for (int i = 0; i < dgv_Inbox.Rows.Count; i++)
            {
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected)
                {
                    NewEmail newEmail = new NewEmail();
                    string from = dgv_Inbox.Rows[i].Cells["From"].Value.ToString();
                    string to = dgv_Inbox.Rows[i].Cells["To"].Value.ToString();
                    string listToAddress = "";
                    if (to.Contains(","))
                    {
                        string[] listTo = to.Split(",".ToCharArray());
                        for (int k = 0; k < listTo.Length; k++)
                            if (listTo[k] != emailName)
                                listToAddress += "," + listTo[k];
                    }

                    string cc = dgv_Inbox.Rows[i].Cells["CC"].Value.ToString();
                    string listCcAddress = "";
                    if (cc.Contains(","))
                    {
                        string[] listCc = cc.Split(",".ToCharArray());
                        for (int k = 0; k < listCc.Length; k++)
                            if (listCc[k] != emailName)
                                listCcAddress += "," + listCc[k];
                    }

                    if (from.Contains("<") && from.Contains(">"))
                    {
                        string fromAddress = from.Substring(from.LastIndexOf("<") + 1);
                        newEmail.txt_To.Text = fromAddress.Remove(fromAddress.Length - 1);
                    }
                    else
                        newEmail.txt_To.Text = from;
                    newEmail.txt_To.Text += listToAddress + listCcAddress;
                    newEmail.cb_From.Text = emailName;
                    newEmail.txt_Subject.Text = dgv_Inbox.Rows[i].Cells["Subject"].Value.ToString();
                    newEmail.ShowDialog();
                }
            }
        }

        private void txt_Email_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
                txt_Password.Focus();
        }

        private void txt_Password_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
                txt_RePassword.Focus();
            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Left)
                txt_Email.Focus();
        }

        private void txt_RePassword_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
                txt_SmtpHost.Focus();
            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Left)
                txt_Password.Focus();
        }

        private void txt_SmtpHost_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
                txt_SmtpPort.Focus();
            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Left)
                txt_RePassword.Focus();
        }

        private void txt_SmtpPort_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
                txt_Pop3Host.Focus();
            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Left)
                txt_SmtpHost.Focus();
        }

        private void txt_Pop3Host_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
                txt_Pop3Port.Focus();
            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Left)
                txt_SmtpPort.Focus();
        }

        private void txt_Pop3Port_KeyDown(object sender, KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Down || e.KeyCode == Keys.Right || e.KeyCode == Keys.Enter)
                btn_Ok.Focus();
            if (e.KeyCode == Keys.Up || e.KeyCode == Keys.Left)
                txt_Pop3Host.Focus();
        }

        //Forward mail
        private void barButtonItem7_ItemClick(object sender, DevExpress.XtraBars.ItemClickEventArgs e)
        {
            for (int i = 0; i < dgv_Inbox.Rows.Count; i++)
            {
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected)
                {
                    NewEmail newEmail = new NewEmail();
                    newEmail.cb_From.SelectedText = cb_Account_Inbox.Text;
                    newEmail.txt_Subject.Text = "FW: " + dgv_Inbox.Rows[i].Cells["Subject"].Value.ToString();
                    string from = dgv_Inbox.Rows[i].Cells["From"].Value.ToString();
                    if (from.Contains("<") && from.Contains(">"))
                    {
                        string fromAddress = from.Substring(from.LastIndexOf("<") + 1);
                        from = fromAddress.Remove(fromAddress.Length - 1);
                    }
                    string extendBody = "From: " + from + "<br/> Sent: " + dgv_Inbox.Rows[i].Cells["DateSent"].Value.ToString() + "<br/> To: " + 
                        dgv_Inbox.Rows[i].Cells["To"].Value.ToString() + "<br/> Subject: " + dgv_Inbox.Rows[i].Cells["Subject"].Value.ToString();
                    if (dgv_Inbox.Rows[i].Cells["CC"].Value.ToString() != "")
                        extendBody += "<br/> Cc: " + dgv_Inbox.Rows[i].Cells["CC"].Value.ToString();
                    newEmail.richEditControl_Body.HtmlText = extendBody + "<br/>" + dgv_Inbox.Rows[i].Cells["Body"].Value.ToString();
                    newEmail.ShowDialog();
                }
            }
        }

        //Click menu Reply
        private void toolStripMenuItem_Reply_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dgv_Inbox.Rows.Count; i++)
            {
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected)
                {
                    NewEmail newEmail = new NewEmail();
                    string from = dgv_Inbox.Rows[i].Cells["From"].Value.ToString();
                    if (from.Contains("<") && from.Contains(">"))
                    {
                        string fromAddress = from.Substring(from.LastIndexOf("<") + 1);
                        newEmail.txt_To.Text = fromAddress.Remove(fromAddress.Length - 1);
                    }
                    else
                        newEmail.txt_To.Text = from;
                    newEmail.cb_From.Text = emailName;
                    newEmail.txt_Subject.Text = dgv_Inbox.Rows[i].Cells["Subject"].Value.ToString();
                    newEmail.ShowDialog();
                }
            }
        }
        //Click menu Reply all
        private void toolStripMenuItem_ReplyAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dgv_Inbox.Rows.Count; i++)
            {
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected)
                {
                    NewEmail newEmail = new NewEmail();
                    string from = dgv_Inbox.Rows[i].Cells["From"].Value.ToString();
                    string to = dgv_Inbox.Rows[i].Cells["To"].Value.ToString();
                    string listToAddress = "";
                    if (to.Contains(","))
                    {
                        string[] listTo = to.Split(",".ToCharArray());
                        for (int k = 0; k < listTo.Length; k++)
                            if (listTo[k] != emailName)
                                listToAddress += "," + listTo[k];
                    }

                    string cc = dgv_Inbox.Rows[i].Cells["CC"].Value.ToString();
                    string listCcAddress = "";
                    if (cc.Contains(","))
                    {
                        string[] listCc = cc.Split(",".ToCharArray());
                        for (int k = 0; k < listCc.Length; k++)
                            if (listCc[k] != emailName)
                                listCcAddress += "," + listCc[k];
                    }

                    if (from.Contains("<") && from.Contains(">"))
                    {
                        string fromAddress = from.Substring(from.LastIndexOf("<") + 1);
                        newEmail.txt_To.Text = fromAddress.Remove(fromAddress.Length - 1);
                    }
                    else
                        newEmail.txt_To.Text = from;
                    newEmail.txt_To.Text += listToAddress + listCcAddress;
                    newEmail.cb_From.Text = emailName;
                    newEmail.txt_Subject.Text = dgv_Inbox.Rows[i].Cells["Subject"].Value.ToString();
                    newEmail.ShowDialog();
                }
            }
        }
        //Click menu Forward
        private void toolStripMenuItem_Forward_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < dgv_Inbox.Rows.Count; i++)
            {
                if (dgv_Inbox.Rows[i].Cells["Selected"].Selected || dgv_Inbox.Rows[i].Cells["Subject"].Selected ||
                    dgv_Inbox.Rows[i].Cells["From"].Selected || dgv_Inbox.Rows[i].Cells["DateSent"].Selected)
                {
                    NewEmail newEmail = new NewEmail();
                    newEmail.cb_From.SelectedText = cb_Account_Inbox.Text;
                    newEmail.txt_Subject.Text = "FW: " + dgv_Inbox.Rows[i].Cells["Subject"].Value.ToString();
                    string from = dgv_Inbox.Rows[i].Cells["From"].Value.ToString();
                    if (from.Contains("<") && from.Contains(">"))
                    {
                        string fromAddress = from.Substring(from.LastIndexOf("<") + 1);
                        from = fromAddress.Remove(fromAddress.Length - 1);
                    }
                    string extendBody = "From: " + from + "<br/> Sent: " + dgv_Inbox.Rows[i].Cells["DateSent"].Value.ToString() + "<br/> To: " +
                        dgv_Inbox.Rows[i].Cells["To"].Value.ToString() + "<br/> Subject: " + dgv_Inbox.Rows[i].Cells["Subject"].Value.ToString();
                    if (dgv_Inbox.Rows[i].Cells["CC"].Value.ToString() != "")
                        extendBody += "<br/> Cc: " + dgv_Inbox.Rows[i].Cells["CC"].Value.ToString();
                    newEmail.richEditControl_Body.HtmlText = extendBody + "<br/>" + dgv_Inbox.Rows[i].Cells["Body"].Value.ToString();
                    newEmail.ShowDialog();
                }
            }
        }
    }
}
